﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;

namespace ASmile.ORM.ADO
{
    public class SQLiteHelper : IDBHelper
    {
        public SQLiteHelper(string connStr)
            : base(connStr)
        { }

        SQLiteConnection _DBConnectionObj;
        SQLiteCommand _DbCommandObj;
        SQLiteDataAdapter _DbDataAdapterObj;

        bool CmdDisposed { set; get; } = false;

        public override string ParamSign => Common.PARAMSIGN_SQLITE;

        public override DbConnection DBConnectionObj
        {
            get
            {
                if (_DBConnectionObj == null)
                {
                    _DBConnectionObj = new SQLiteConnection(ConnStr);
                }
                return _DBConnectionObj;
            }
        }

        public override DbCommand DbCommandObj
        {
            get
            {
                if (_DbCommandObj == null || CmdDisposed)
                {   
                    _DbCommandObj = new SQLiteCommand();
                    _DbCommandObj.Disposed -= _DbCommandObj_Disposed;
                    _DbCommandObj.Disposed += _DbCommandObj_Disposed;
                    CmdDisposed = false;
                }
                return _DbCommandObj;
            }
        }

        private void _DbCommandObj_Disposed(object sender, EventArgs e)
        {
            CmdDisposed = true;
        }

        protected internal override DbDataAdapter DbDataAdapterObj
        {
            get
            {
                if (_DbDataAdapterObj == null)
                {
                    _DbDataAdapterObj = new SQLiteDataAdapter();
                }
                return _DbDataAdapterObj;
            }
        }

        public override void TransStart(IsolationLevel level)
        {
            base.TransStart();
        }

        public override DbParameter CreateDbParameter(string paramName, object paramValue)
        {
            return new SQLiteParameter(paramName, paramValue);
        }
        //#if !NET40
#if !NETSTANDARD
        /// <summary>
        /// 修改sqlite数据库密码
        /// </summary>
        /// <param name="connStr">连接字符串</param>
        /// <param name="newPassword">要设置的新密码</param>
        public static void ChangePassword(string connStr, string newPassword)
        {
            using (SQLiteConnection conn = new SQLiteConnection(connStr))
            {
                try
                {
                    conn.Open();
                    conn.ChangePassword(newPassword);
                    conn.Close();
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
            }
        }
#endif

        /// <summary>
        /// 批量插入
        /// </summary>
        public override int BulkInsert(DataTable dt)
        {
            throw new NotImplementedException("sqlite 不支持批量插入操作，直接使用事务操作");
        }
    }
}